<template>
  <div class="reset-container">
    <!-- 左侧标题区域 -->
    <div class="title-section">
      <div class="title-content">
        <h1 class="main-title">密码重置</h1>
        <div class="title-description">
          <p>通过邮箱验证重置您的密码</p>
        </div>
      </div>
    </div>
    
    <!-- 右侧重置框 -->
    <div class="reset-box">
      <div class="reset-header">
        <h2>{{ currentStep === 1 ? '验证邮箱' : '重置密码' }}</h2>
        <p>{{ currentStep === 1 ? '请输入您的邮箱地址，我们将发送验证码' : '请输入验证码和新密码' }}</p>
      </div>
      
      <!-- 步骤 1: 发送验证码 -->
      <el-form 
        v-if="currentStep === 1"
        ref="emailFormRef"
        :model="emailForm" 
        :rules="emailRules"
        class="reset-form"
        @submit.prevent="handleSendCode"
      >
        <el-form-item prop="email">
          <el-input 
            v-model="emailForm.email" 
            placeholder="请输入您的邮箱地址"
            prefix-icon="Message"
            size="large"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSendCode" 
            :loading="sendCodeLoading"
            size="large"
            class="reset-button"
          >
            发送验证码
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="default" 
            @click="goBack"
            size="large"
            class="back-button"
          >
            返回登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 步骤 2: 验证码和重置密码 -->
      <el-form 
        v-if="currentStep === 2"
        ref="resetFormRef"
        :model="resetForm" 
        :rules="resetRules"
        class="reset-form"
        @submit.prevent="handleResetPassword"
      >
        <el-form-item>
          <div class="email-display">
            <span>验证码已发送至：{{ maskEmail(emailForm.email) }}</span>
            <el-button type="text" @click="goBackToStep1">更换邮箱</el-button>
          </div>
        </el-form-item>
        
        <el-form-item prop="verificationCode">
          <el-input 
            v-model="resetForm.verificationCode" 
            placeholder="请输入6位验证码"
            prefix-icon="Key"
            size="large"
            maxlength="6"
          />
        </el-form-item>
        
        <el-form-item prop="newPassword">
          <el-input 
            v-model="resetForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="resetForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleResetPassword" 
            :loading="resetLoading"
            size="large"
            class="reset-button"
          >
            重置密码
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <div class="resend-section">
            <span v-if="countdown > 0">{{ countdown }}秒后可重新发送</span>
            <el-button 
              v-else
              type="text" 
              @click="handleResendCode"
              :loading="sendCodeLoading"
            >
              重新发送验证码
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { authAPI } from '../../api/hy.ts'

// 类型定义
interface EmailFormData {
  email: string
}

interface ResetFormData {
  verificationCode: string
  newPassword: string
  confirmPassword: string
}

// API响应类型
interface ApiResponse {
  code: number
  message: string
  data: any
}

// 自定义验证器类型
type ValidatorRule = (rule: any, value: any, callback: (error?: Error) => void) => void

const router = useRouter()

// 当前步骤
const currentStep = ref<number>(1)

// 表单引用
const emailFormRef = ref<FormInstance>()
const resetFormRef = ref<FormInstance>()

// 加载状态
const sendCodeLoading = ref<boolean>(false)
const resetLoading = ref<boolean>(false)

// 倒计时
const countdown = ref<number>(0)
let countdownTimer: TimerHandle | null = null

// 邮箱表单数据
const emailForm = reactive<EmailFormData>({
  email: ''
})

// 重置表单数据
const resetForm = reactive<ResetFormData>({
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 邮箱表单验证规则
const emailRules: FormRules<EmailFormData> = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 重置表单验证规则
const resetRules: CustomFormRules<ResetFormData> = {
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码必须是6位', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码只能是数字', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    { max: 20, message: '密码长度不能超过20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: ((rule: any, value: string, callback: (error?: Error) => void): void => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }) as ValidatorRule,
      trigger: 'blur'
    }
  ]
}

// 邮箱脱敏显示函数 - 使用泛型约束
const maskEmail = <T extends string>(email: T): string => {
  if (!email) return ''
  const emailParts = email.split('@') as [string, string]
  const [name, domain] = emailParts
  
  if (name.length <= 2) {
    return `${name[0]}***@${domain}`
  }
  return `${name.slice(0, 2)}***@${domain}`
}

// 开始倒计时函数
const startCountdown = (): void => {
  countdown.value = 60
  countdownTimer = setInterval((): void => {
    countdown.value--
    if (countdown.value <= 0) {
      clearCountdown()
    }
  }, 1000)
}

// 清除倒计时函数
const clearCountdown = (): void => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
    countdown.value = 0
  }
}

// 发送验证码 - 使用泛型API响应
const handleSendCode = async (): Promise<void> => {
  if (!emailFormRef.value) return
  
  try {
    await emailFormRef.value.validate()
    sendCodeLoading.value = true
    
    const response: ApiResponse<SendCodeResponseData> = await authAPI.sendResetCode(emailForm.email)
    
    if (response.code === 200) {
      ElMessage.success('验证码发送成功，请查收邮件')
      currentStep.value = 2
      startCountdown()
    } else {
      ElMessage.error(response.message || '验证码发送失败')
    }
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : '验证码发送失败'
    ElMessage.error(errorMessage)
    console.error('发送验证码失败:', error)
  } finally {
    sendCodeLoading.value = false
  }
}

// 重新发送验证码 - 使用泛型API响应
const handleResendCode = async (): Promise<void> => {
  try {
    sendCodeLoading.value = true
    
    const response: ApiResponse<SendCodeResponseData> = await authAPI.sendResetCode(emailForm.email)
    
    if (response.code === 200) {
      ElMessage.success('验证码重新发送成功')
      startCountdown()
    } else {
      ElMessage.error(response.message || '验证码发送失败')
    }
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : '验证码发送失败'
    ElMessage.error(errorMessage)
    console.error('重新发送验证码失败:', error)
  } finally {
    sendCodeLoading.value = false
  }
}

// 重置密码 - 使用泛型API响应和类型安全的参数
const handleResetPassword = async (): Promise<void> => {
  if (!resetFormRef.value) return
  
  try {
    await resetFormRef.value.validate()
    resetLoading.value = true
    
    const requestData = {
      email: emailForm.email,
      verificationCode: resetForm.verificationCode,
      newPassword: resetForm.newPassword
    } as const
    
    const response: ApiResponse<ResetPasswordResponseData> = await authAPI.resetPassword(requestData)
    
    if (response.code === 200) {
      ElMessage.success('密码重置成功，请使用新密码登录')
      await router.push('/login')
    } else {
      // 根据不同的错误代码显示相应的错误信息
      if (response.code === 400) {
        if (response.message.includes('验证码')) {
          ElMessage.error('验证码错误，请重新输入')
        } else if (response.message.includes('过期')) {
          ElMessage.error('验证码已过期，请重新获取')
        } else if (response.message.includes('密码重复')) {
          ElMessage.error('新密码与旧密码重复')
        } else {
          ElMessage.error(response.message || '请求参数错误')
        }
      } else if (response.code === 404) {
        ElMessage.error('用户不存在')
      } else {
        ElMessage.error(response.message || '密码重置失败')
      }
    }
  } catch (error: any) {
    // 处理HTTP错误响应
    if (error.response && error.response.data) {
      const errorData = error.response.data
      
      if (error.response.status === 400) {
        if (errorData.message && errorData.message.includes('验证码错误')) {
          ElMessage.error('验证码错误，请重新输入')
        } else if (errorData.message && errorData.message.includes('验证码已过期')) {
          ElMessage.error('验证码已过期，请重新获取')
        } else if (errorData.message && errorData.message.includes('验证码')) {
          ElMessage.error('验证码无效，请重新输入')
        } else {
          ElMessage.error(errorData.message || '请求参数错误')
        }
      } else if (error.response.status === 404) {
        ElMessage.error('用户不存在')
      } else {
        ElMessage.error(errorData.message || '密码重置失败')
      }
    } else {
      const errorMessage = error instanceof Error ? error.message : '密码重置失败'
      ElMessage.error(errorMessage)
    }
    
    console.error('密码重置失败:', error)
  } finally {
    resetLoading.value = false
  }
}

// 返回第一步 - 使用泛型重置函数
const resetFormData = <T extends Record<string, any>>(formData: T, defaultValues: Partial<T>): void => {
  Object.keys(defaultValues).forEach(key => {
    if (key in formData) {
      (formData as any)[key] = defaultValues[key]
    }
  })
}

const goBackToStep1 = (): void => {
  currentStep.value = 1
  
  // 使用泛型重置表单数据
  resetFormData(resetForm, {
    verificationCode: '',
    newPassword: '',
    confirmPassword: ''
  })
  
  clearCountdown()
}

// 返回登录页
const goBack = (): void => {
  router.push('/login')
}

// 组件卸载时清理定时器
onUnmounted((): void => {
  clearCountdown()
})
</script>

<style lang="scss" scoped>
// 变量定义
$primary-color: #e56565;
$secondary-color: #c44545;
$text-primary: #303133;
$text-secondary: #909399;
$border-color: #e4e7ed;
$border-light: #f0f0f0;
$white: #ffffff;
$black: #000000;
$shadow-light: rgba(0, 0, 0, 0.1);
$shadow-primary: rgba(229, 101, 101, 0.2);
$shadow-primary-hover: rgba(229, 101, 101, 0.4);

.reset-container {
  height: 100vh;
  background: url('https://cdn8.axureshop.com/demo/1992135/images/%E7%99%BB%E5%BD%95_2/u12187_state0.png') no-repeat center center;
  background-size: cover;
  display: flex;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba($black, 0.3);
    pointer-events: none;
  }
}

// 左侧标题区域
.title-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 1;
  padding: 32px;

  .title-content {
    text-align: center;
    color: $white;

    .main-title {
      font-size: 72px;
      font-weight: 700;
      margin: 0 0 16px 0;
      text-shadow: 2px 2px 4px rgba($black, 0.5);
    }

    .title-description {
      font-size: 28px;
      line-height: 1.6;
      opacity: 0.8;

      p {
        margin: 8px 0;
      }
    }
  }
}

// 右侧重置框
.reset-box {
  width: 496px;
  height: 100vh;
  background: rgba($white, 0.95);
  backdrop-filter: blur(10px);
  border-left: 1px solid rgba($white, 0.2);
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 256px 48px;
  position: relative;
  z-index: 1;

  .reset-header {
    text-align: center;
    margin-bottom: 32px;

    h2 {
      margin: 0 0 8px 0;
      color: $text-primary;
      font-size: 28px;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: $text-secondary;
      font-size: 14px;
    }
  }

  .reset-form {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;

    .el-form-item {
      margin-bottom: 24px;
    }
  }

  .reset-button {
    width: 100%;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 8px;
    background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
    border: none;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px $shadow-primary-hover;
    }
  }

  .back-button {
    width: 100%;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 8px;
    border: 1px solid $border-color;
    transition: all 0.3s ease;

    &:hover {
      border-color: $primary-color;
      color: $primary-color;
    }
  }

  .email-display {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f8f9fa;
    border-radius: 8px;
    color: $text-secondary;
    font-size: 14px;
  }

  .resend-section {
    text-align: center;
    color: $text-secondary;
    font-size: 14px;
  }
}

// 输入框样式优化
:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px $shadow-light;
  border: 1px solid $border-color;
  transition: all 0.3s ease;

  &:hover {
    border-color: $primary-color;
    box-shadow: 0 2px 12px $shadow-primary;
  }

  &.is-focus {
    border-color: $primary-color;
    box-shadow: 0 0 0 2px $shadow-primary;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .reset-container {
    flex-direction: column;
  }
  
  .title-section {
    flex: none;
    height: 40vh;
    padding: 16px;

    .title-content {
      .main-title {
        font-size: 32px;
      }
    }
  }
  
  .reset-box {
    width: 100%;
    height: 60vh;
    padding: 32px;
  }
}
</style> 